//app.js
var http = require('./utils/httpHelper.js'), code_type = 0, inviter_id = 0, need_redirect = false, scene = 0;
var config = require('./config.js')
App({
  onLaunch: function (options) {
    scene = options.scene;
    //来自用户直接分享商品的链接
    if (options.query.good_id && options.query.inviter_id && options.query.is_invite == 1) {
      code_type = 16;
      inviter_id = options.query.inviter_id;
      good_id = options.query.good_id,
        need_redirect = true
    }
    //仅仅来自用户分享无商品信息
    else if (options.query.inviter_id && !options.query.good_id && options.query.is_invite == 1) {
      code_type = 16;
      need_redirect = false;
      inviter_id = options.query.inviter_id;
    }
    //来自二维码的分销
    else {
      if (options.query.scene && isNaN(options.query.scene)) {
        var s = decodeURIComponent(options.query.scene);
        //console.log(decodeURIComponent(s))
        var and = new RegExp('@');
        var qtype = new RegExp('type');
        var inviter = new RegExp('inviter');
        var good = new RegExp('good');
        //内部类型注册;var s = 'type_53';
        if (qtype.test(s) && !inviter.test(s) && !good.test(s)) {
          var arr = s.split('_');
          code_type = arr[1];
          need_redirect = false;
        }
        //分销注册不携带商品信息;var s='type_53@member_888';
        else if (qtype.test(s) && inviter.test(s) && !good.test(s)) {
          var arr = s.split('@');
          var arr_type = arr[0].split('_');
          var arr_inviter = arr[1].split('_');
          code_type = arr_type[1];
          inviter_id = arr_inviter[1];
          need_redirect = false;
        }
        //分销注册携带商品信息;var s='type_53@member_888@good_1';
        else if (qtype.test(s) && inviter.test(s) && good.test(s)) {
          var arr = s.split('@');
          var arr_type = arr[0].split('_');
          var arr_inviter = arr[1].split('_');
          var good_arr = arr[2].split('_');
          good_id = good_arr[1];
          code_type = arr_type[1];
          inviter_id = arr_inviter[1];
          need_redirect = true;
        }
      } else {
        code_type = 0;
        inviter_id = 0;
        need_redirect = false;
      }
    }
    this.onShow()
  },
  onShow: function () {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    var res = wx.getStorageInfoSync()
    if (!rd_session) {
      wx.clearStorageSync();
      self.login(code_type, inviter_id, scene);
    } else {
      wx.checkSession({
        success: function () {
          self.check_rdsession();
        },
        fail: function () {
          //登录态过期
          self.login(code_type, inviter_id, scene);
        }
      })
    }
  },
 //code_type：扫码类型；inviter_id：邀请者id；scene：入口场景
  login: function (code_type, inviter_id, scene) {
    var self = this;
    console.log("login..")
    wx.login({
      success: function (res) {
        console.log("wxloginsuccess")
        if (res.code) {
          var code = res.code;
          wx.getUserInfo({
            success: function (res) {
              console.log("success")
              var rawData = res['rawData'];
              var signature = res['signature'];
              var encryptData = res['encryptData'];
              var encryptedData = res['encryptedData'];
              var iv = res['iv'];
              //发起网络请求
              var data = {
                scene: scene,
                code_type: code_type,
                inviter_id: inviter_id,
                "mchid": 'd072f71878ca8a3288b05bb50c0ecc65',
                "code": code,
                "rawData": rawData,
                "signature": signature,
                "encryptData": encryptData,
                'iv': iv,
                'encryptedData': encryptedData
              }
              wx.request({
                url: config.HTTP_BASE_URL + 'wxlogin',
                method: 'POST',
                data: data,
                success: function (ress) {
                  if (ress.data.message === 'success') {
                    self.globalData.userInfo = ress.data;
                    self.globalData.hasLogin = true;
                    var rd = ress.data.rd_session;
                    wx.setStorageSync('rd_session', rd);
                    wx.setStorageSync('userinfo', ress.data);
                    //登录成功后做响应跳转
                    if (need_redirect) {
                      wx.navigateTo({
                        url: '/pages/goods/goods_detail_buy?id=' + good_id
                      })
                    }
                  } else {
                    wx.showModal({
                      title: '提醒',
                      content: '第三方登录失败！',
                    })
                  }
                }
              })
            },
            fail: function () {
              console.log("err")
              wx.showModal({
                title: '警告',
                content: '您点击了拒绝授权,将无法正常使用菜花国际，后期想要使用菜花国际，需在微信【发现】——【小程序】——删掉【菜花国际浴足连锁】，重新搜索授权登陆才可使用。',
              })
            }
          });
        } else {
          console.log('获取用户登录态失败！' + res.errMsg)
        }
      },
      fail: function (e) {
        console.log("wxloginfail")
      }
    });
  },
  // shareApp: function (res) {
  //   return {
  //     title: '有意思的玩具社区~',
  //     path: '/pages/index/index',
  //     success: function (res) {
  //       // 转发成功
  //     },
  //     fail: function (res) {
  //       // 转发失败
  //     }
  //   }
  // },
  check_rdsession: function () {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    http.httpPost("/check_login", { rd_session: rd_session }, function (res) {
      if (res.message == 'offline') {
        wx.clearStorageSync();
        wx.removeStorageSync("rd_session");
        self.login();
      } else {
        self.globalData.hasLogin = true;
        self.globalData.userInfo = wx.getStorageSync('userinfo');

      }
    })
  },
  check_online: function () {
    var self = this;
    var rd_session = wx.getStorageSync('rd_session');
    if (!rd_session) {
      self.login();
    } else {
      wx.checkSession({
        success: function () {
          self.check_rdsession();
        },
        fail: function () {
          //登录态过期
          self.login();
        }
      })
    }
  },
  checkUser(cb) {
    var rd_session = wx.getStorageSync('rd_session');
    http.httpPost("check_info", { rd_session: rd_session }, function (res) {
      console.log(res.data)
      typeof cb == "function" && cb(res.data, "");
    })
  },
  checkVip(cb) {
    var rd_session = wx.getStorageSync('rd_session');
    http.httpPost("check_vip", { rd_session: rd_session }, function (res) {
      console.log(res.data)
      typeof cb == "function" && cb(res.data, "");
    })
  },
  buildpayparam: function (order_no, openid) {
    wx.request({
      url: config.BASE_URL + 'WePay/build_payparam',
      method: 'POST',
      // header: {
      //   'content-type': 'application/x-www-form-urlencoded'
      // },
      data: { order_no: order_no, openid: openid },
      success: function (res) {

        return res.data;
      },
    })


  },
  // 调用微信支付接口课程支付
  wxPayClass: function (para) {
    var _this = this;
    wx.request({
      url: config.BASE_URL + 'Api/build_class_payparam',
      method: 'POST',
      data: { order_no: para.order_no, openid: para.openid, mchid:'d072f71878ca8a3288b05bb50c0ecc65',
        rd_session: wx.getStorageSync('rd_session')},
      success: function (res) {
        var param = res.data;
        console.log(param);
        wx.requestPayment({
          'timeStamp': param.timeStamp,
          'nonceStr': param.nonceStr,
          'package': param.package,
          'signType': 'MD5',
          'paySign': param.paySign,
          success: function (res) {
            typeof para.success === 'function' && para.success(res);
          },
          fail: function (res) {
            typeof para.fail === 'function' && para.fail();
          }
        })
      },
    })
  },
  // 调用微信支付接口商品支付
  wxPayGood: function (para) {
    var _this = this;
    wx.request({
      url: config.BASE_URL + 'Api/build_payparam',
      method: 'POST',
      data: {
        order_no: para.order_no, openid: para.openid, mchid: 'd072f71878ca8a3288b05bb50c0ecc65',
        rd_session: wx.getStorageSync('rd_session')
      },
      success: function (res) {
        var param = res.data;
        console.log(param);
        wx.requestPayment({
          'timeStamp': param.timeStamp,
          'nonceStr': param.nonceStr,
          'package': param.package,
          'signType': 'MD5',
          'paySign': param.paySign,
          success: function (res) {
            typeof para.success === 'function' && para.success(res);
          },
          fail: function (res) {
            typeof para.fail === 'function' && para.fail();
          }
        })
      },
    })
  },
  wxPaySuccess: function (param) {
    var orderId = param.orderId,
      goodsType = param.goodsType,
      formId = param.package.substr(10),
      t_num = goodsType == 1 ? 'AT0104' : 'AT0009';
    //发送模板消息通知
    //支付成功 跳转上一页
    wx.navigateBack({
      delta: 1
    })
  },

  wxPayClassok: function (param) {
    let da = { 
      order_id :param.order_no,
      form_id : param.package.substr(10),
      rd_session : wx.getStorageSync('rd_session'),
      openid : this.globalData.userInfo.openId
    } 
    //发送模板消息通知
    wx.request({
      url: config.BASE_URL + 'Api/send_template_message_class',
      method: 'POST',
      data: da,
      success: function (res) {
        var param = res.data;
        console.log(param);
      },
    })
  },
  wxPayGoodok: function (param) {
    let da = {
      order_id: param.order_no,
      form_id: param.package.substr(10),
      rd_session: wx.getStorageSync('rd_session'),
      openid: this.globalData.userInfo.openId
    }
    //发送模板消息通知
    wx.request({
      url: config.BASE_URL + 'Api/send_template_message_product',
      method: 'POST',
      data: da,
      success: function (res) {
        var param = res.data;
        console.log(param);
      },
    })
  },
  wxPayFail: function (param, errMsg) {
    var orderId = param.orderId,
      formId = param.package.substr(10);

    //发送模板消息

  },
  check_empty: function (v) {
    switch (typeof v) {
      case 'undefined':
        return true;
      case 'string':
        if (v.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g, '').length == 0) return true;
        break;
      case 'boolean':
        if (!v) return true;
        break;
      case 'number':
        if (0 === v || isNaN(v)) return true;
        break;
      case 'object':
        if (null === v || v.length === 0) return true;
        for (var i in v) {
          return false;
        }
      default:
        return true;
    }
    return false;
  },
  //检查手机号 是返回true
  checkPhone(phone) {
    if (!(/^1[34578]\d{9}$/.test(phone))) {
      return false;
    } else {
      return true;
    }
  },
  sendTemplate: function (formId, templateData, success, fail) {
    var app = getApp();
    this.getJSON({
      url: '/WxAppApi/sendTemplate',
      data: {
        rd_session: app.rd_session,
        form_id: formId,
        data: templateData,
      },
      success: success,   // errorcode==0时发送成功
      fail: fail
    });
  },
  //自适应图片
  fixImgW(e, width) {
    var _this = this;
    var $width = e.detail.width,    //获取图片真实宽度  
      $height = e.detail.height,
      ratio = $width / $height;   //图片的真实宽高比例  
    var viewWidth = width,           //设置图片显示宽度，  
      viewHeight = width / ratio;    //计算的高度值
    return viewHeight
  },

  globalData: {
    appid: "",
    userInfo: ''
  }
})